package com.linh.bus.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;

public class HttpRequestExecutorImpl implements HttpRequestExecutor {

	private HttpClient httpClient;

	public HttpRequestExecutorImpl(HttpClient httpClient) {
		super();
		this.httpClient = httpClient;
	}

	public String get(String url) throws HttpException {
		HttpGet httpGet = new HttpGet(url);
		return doGet(httpGet, url);
	}

	protected String doGet(HttpGet httpGet, String url) throws HttpException {
		HttpEntity httpEntity = null;
		try {
			HttpResponse httpResponse = httpClient.execute(httpGet);
			int responseCode = httpResponse.getStatusLine().getStatusCode();
			if (responseCode == HttpStatus.SC_BAD_REQUEST) {
				throw new HttpException("Failed to get from url " + url);
			}
			httpEntity = httpResponse.getEntity();
			String html = EntityUtils.toString(httpEntity);
			return html;

		} catch (Exception ex) {
			throw new HttpException(ex);
		} finally {
			if (httpEntity != null) {
				try {
					EntityUtils.consume(httpEntity);
				} catch (Exception ex) {
					throw new HttpException(ex);
				}
			}
		}
	}

}
